package org.example.day11;

import javafx.concurrent.Service;

import javax.swing.plaf.TableHeaderUI;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.10.3: getWaitQueueLength(condition)
 *      获取某锁的某condition下有几个线程执行了await处于等待状态
 */
public class MyThread9 {
    private ReentrantLock lock = new ReentrantLock();
    private Condition newConditionA = lock.newCondition();
    private Condition newConditionB = lock.newCondition();

    public void waitMethod() {
        try {
            lock.lock();
            newConditionA.await();
            System.out.println("第一个等待线程继续执行~");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("有③" + lock.getWaitQueueLength(newConditionA) + "个线程正在等待newConditionA");
            lock.unlock();
        }
    }

    public void notifyMethod() {
        try {
            lock.lock();
            System.out.println("有①" + lock.getWaitQueueLength(newConditionA) + "个线程正在等待newConditionA");
            System.out.println("有" + lock.getWaitQueueLength(newConditionB) + "个线程正在等待newConditionB");
            newConditionA.signal();
            //唤醒等待线程后，即使等待线程未获取到cpu,也不属于等待状态了.属于就绪状态.
            System.out.println("有②" + lock.getWaitQueueLength(newConditionA) + "个线程正在等待newConditionA");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final MyThread9 m9 = new MyThread9();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                m9.waitMethod();
            }
        };
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
        Thread.sleep(2000);
        m9.notifyMethod();
    }
}
